<?php
namespace Data;

use Data\Drive\DataCache;

class Update extends \Data
{
    public static function Run($conf)
    {
        if (!is_array($conf)) {
            self::Error("更新必须为数组格式", __FILE__, __LINE__);
        }
        $sql  = self::toSql($conf);
        $num  = self::$db->exec($sql);
        $code = self::$db->errorCode();
        if ($code != 00000) {
            $info = self::$db->errorInfo();
            self::Error(json_encode($info) . "\r\n" . $sql, __FILE__, __LINE__);
        }
        DataCache::clearCache($conf['table']);
        return ["state" => "ok", "msg" => "操作成功"];
    }

    private static function toSql($conf)
    {
        /*$set = json_encode($conf['set'], JSON_UNESCAPED_UNICODE);
        $set = preg_replace(["/[\{\}]/", "/\"([^\"]+)\":/", "/\"([0-9]+)\"/", "/\"/"], ["", "`$1`=", "$1", "'"], $set);*/
        $pattern     = ["/^array\s?\(/", "/\)$/", "/[\r\n]/", "/^\s+/", "/,$/", "/'([^']+)'\s{1,}=>/", "/\s{2,}/", "/'(-?[0-9]+\.?[0-9]+)'/"];
        $replacement = ["", "", "", "", "", "$1 =", " ", "$1"];
        $set         = preg_replace($pattern, $replacement, var_export($conf['set'], true));
        return "UPDATE {$conf['table']} SET {$set} WHERE {$conf['where']}";
    }
}
